import React , {FC , ReactElement , useCallback , useEffect, useReducer}from 'react';
import TdInput from './input'
import TdList from './List'
import { todoReducer } from './reducer';
import {ITodo,IState, ACTION_TYPE} from './typings'
// 惰性初始化
function init (initTodoList:ITodo[]):IState{
    return{
        todoList:initTodoList
    }
}
const TodoList:FC = (): ReactElement => {
    const [state,dispatch] = useReducer(todoReducer,[],init)
    useEffect(() => {
        const todoList = JSON.parse(localStorage.getItem('todolist') || '[]')
        dispatch({
            type: ACTION_TYPE.INIT_TODOLIST,
            payload:todoList
        })
    }, [])
    useEffect(()=>{
        localStorage.setItem('todolist',JSON.stringify(state.todoList))
    },[state.todoList])
    const addTodo = useCallback((todo:ITodo) => {
        dispatch({
            type:ACTION_TYPE.ADD_TODO,
            payload:todo
        })
    },[])
    const removeTodo = useCallback((id:number) => {
        dispatch({
            type:ACTION_TYPE.REMOVE_TODO,
            payload:id
        })
    },[])
    const toggleTodo = useCallback((id:number) => {
        dispatch({
            type:ACTION_TYPE.TOGGLE_TODO,
            payload:id
        })
    },[])
    return (
        <div className="TodoList">
            <TdInput
                addTodo = {addTodo}
                todoList = {state.todoList}
            />
            <TdList
                todoList = {state.todoList}
                removeTodo = {removeTodo}
                toggleTodo = {toggleTodo}
            />
        </div>
    )
}
export default TodoList